<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="mod-sys__dict">
      <el-form :inline="true" :model="dataForm"  @keydown.enter.native.prevent="searchNotice()">
        <el-form-item>
          <el-input v-model="dataForm.describe" placeholder="主题/创建者/内容" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-input v-model="dataForm.createby" placeholder="字典类型" clearable></el-input>
        </el-form-item> -->
        <el-form-item>
          <el-button @click="searchNotice()">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="childHandle()">新增</el-button>
          <!-- <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button> -->
          <!-- <el-button v-if="$hasPermission('sys:dict:save')" type="labelprimary" @click="addOrUpdateHandle()">{{ $t('add')
            }}</el-button> -->
        </el-form-item>
        <el-form-item>
          <el-button  type="danger" :disabled="dataListSelections.length <= 0" @click="deleteHandle()" >批量删除</el-button>
          <!-- <el-button v-if="$hasPermission('sys:dict:delete')" type="danger" @click="deleteHandle()">{{ $t('deleteBatch') }}</el-button> -->
        </el-form-item>
      </el-form>
      <el-table
        
        v-loading="dataListLoading"
        :data="showDataList"
        border
        @refreshDataList="getDataList"
        @selection-change="dataListSelectionChangeHandle"
        
        style="width: 100%;">
        <!-- :default-sort = "{ prop: 'createtime', order: 'descending'}" -->
        <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
        <el-table-column prop="noticeTopic" label="公告主题" header-align="center" align="center" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createby" label="发布者" header-align="center" align="center">
        </el-table-column>
        <el-table-column prop="target" label="发布对象" header-align="center" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.target === 0" size="small" type="success">全体用户</el-tag>
            <el-tag v-else-if="scope.row.target === 1" size="small" type="info">学生</el-tag>
            <el-tag v-else size="small" type="warning">教师</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="sort" label="排序" sortable header-align="center" align="center"></el-table-column> -->
        <!-- sortable :sort-orders="[null, 'ascending', 'descending']" -->
        <el-table-column prop="createtime" label="创建时间" 
         header-align="center" align="center" width="180"></el-table-column>
        <el-table-column  label="操作" fixed="right" header-align="center" align="center" width="150">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="childHandle(scope.row)">修改</el-button>
            <!-- <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button> -->
            <el-button  type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
            <!-- <el-button v-if="$hasPermission('sys:dict:update')" type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">{{ $t('update') }}</el-button>
            <el-button v-if="$hasPermission('sys:dict:delete')" type="text" size="small" @click="deleteHandle(scope.row.id)">{{ $t('delete') }}</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="limit"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="pageSizeChangeHandle"
        @current-change="pageCurrentChangeHandle">
      </el-pagination>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    </div>
  </el-card>
</template>

<script>
import AddOrUpdate from './notice-add-or-update1.vue'
import { addDynamicRoute } from '@/router'
import servicesApi from '@/services/servicesApi'
export default {
  data() {
    return {
      dataForm: {
        id: 0,
        describe: null,
      },               // 查询条件
      showDataList: [],
      dataList: [
        {
          id: 11,
          userId: 0,
          createby: '李西茵',
          username: '2020110228',
          target: 0, //0全体用户，1学生,2教师
          noticeTopic: '关于毕设答辩的通知',
          noticeContent: '',
          createtime: '',
          gmtCreate: '2022-12-10 21:14:10',
          gmtModified: '2022-12-10 21:14:10',
          createtime: '',
          version: 0,
          deleted: 0,
        },
      ],               // 数据列表
      order: '',                  // 排序，asc／desc
      orderField: '',             // 排序，字段
      page: 1,                    // 当前页码
      limit: 10,                  // 每页数
      total: 0,                   // 总条数
      dataListLoading: false,     // 数据列表，loading状态
      dataListSelections: [],     // 数据列表，多选项
      addOrUpdateVisible: false,   // 新增／更新，弹窗visible状态
    }
  },
  created() {
    // console.log('1')
    this.getDataList()
  },
  // mounted(){
  //   // console.log('2')
  //   this.getDataList()
  // },
  activated() {
    // console.log('3')
    this.getDataList()
  },
  components: {
    AddOrUpdate
  },
  methods: {
    // 子级
    childHandle(row) {
      // // console.log(row)
      // 路由参数
      const routeParams = {
        routeName: `${this.$route.name}__${row !== undefined ?row.id:0}`,
        title: `${this.$route.meta.title}-${row !== undefined ?'修改':'新增'}`,
        path: 'Admin/notice-add-or-update',
        params: {
          id: row !==undefined ?row.id:0 
        }
      }
      // 动态路由
      addDynamicRoute(routeParams, this.$router)
    },
    searchNotice() { //全文模糊查询公告
      if (this.dataForm.describe === null || this.dataForm.describe === '') {
        // console.log('查询条件为空')
        return this.getDataList()
      }
      this.dataListLoading = true
      servicesApi.getNoticeList(this.dataForm.describe).then(res => {
        // console.log(res.data)
        let code = res.data.code
        let data = res.data.data
        if (code === 200) {
          this.dataList = data
          this.showDataList = this.dataList.slice((this.page - 1) * this.limit, this.page * this.limit);   // 抓取区间数据
          this.total = data.length
        } else {
          this.dataList = []
          this.showDataList = []
          this.total = 0
        }
        this.dataListLoading = false
      })
    },
    getDataList: function() {//初始化页面获取所有公告
      // this.dataListLoading = true
      // this.total = this.dataList.length
      // this.dataListLoading = false

      this.dataListLoading = true
      servicesApi.getNoticeAll().then(res => {
        // console.log(res.data)
        let code = res.data.code
        let data = res.data.data
        if (code === 200) {
          this.dataList = data
          this.showDataList = this.dataList.slice((this.page - 1) * this.limit, this.page * this.limit);   // 抓取区间数据
          this.total = data.length
        } else {
          this.dataList = []
          this.showDataList=[]
          this.total = 0
        }
        this.dataListLoading = false
      })

      
    },

    // 多选
    dataListSelectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 排序
    dataListSortChangeHandle(data) {
      // if (!data.order || !data.prop) {
      //   this.order = ''
      //   this.orderField = ''
      //   return false
      // }
      // this.order = data.order.replace(/ending$/, '')
      // this.orderField = data.prop.replace(/([A-Z])/g, '_$1').toLowerCase()
      // this.getDataList()
    },
    // 分页, 每页条数
    pageSizeChangeHandle(val) {
      this.page = 1
      this.limit = val
      // this.getDataList()
      this.showDataList = this.dataList.slice((this.page - 1) * this.limit, this.page * this.limit);   // 抓取区间数据
    },
    // 分页, 当前页
    pageCurrentChangeHandle(val) {
      this.page = val
      // this.getDataList()
      this.showDataList = this.dataList.slice((this.page - 1) * this.limit, this.page * this.limit);   // 抓取区间数据
    },
    
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 关闭当前窗口
    closeCurrentTab(data) {
      let tabName = this.$store.state.contentTabsActiveName
      this.$store.state.contentTabs = this.$store.state.contentTabs.filter(item => item.name !== tabName)
      if (this.$store.state.contentTabs.length <= 0) {
        this.$store.state.sidebarMenuActiveName = this.$store.state.contentTabsActiveName = 'home'
        return false
      }
      if (tabName === this.$store.state.contentTabsActiveName) {
        this.$router.push({ name: this.$store.state.contentTabs[this.$store.state.contentTabs.length - 1].name })
      }
    },
    // 删除
    deleteHandle(id) {
      
      let noticeIds = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      // console.log(noticeIds)

      this.$confirm(`确定对[id=${noticeIds.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        servicesApi.deleteNoticeByIds(noticeIds).then(res => {
          if (res.data.code !== 200) {
            return this.$message.error(res.data.msg)
          }
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.getDataList()
            }
          })
        })
      }).catch(() => { })
      // if (this.mixinViewModuleOptions.deleteIsBatch && !id && this.dataListSelections.length <= 0) {
      //   return this.$message({
      //     message: this.$t('prompt.deleteBatch'),
      //     type: 'warning',
      //     duration: 500
      //   })
      // }
      // this.$confirm(this.$t('prompt.info', { 'handle': this.$t('delete') }), this.$t('prompt.title'), {
      //   confirmButtonText: this.$t('confirm'),
      //   cancelButtonText: this.$t('cancel'),
      //   type: 'warning'
      // }).then(() => {
      //   this.$http.delete(
      //     `${this.mixinViewModuleOptions.deleteURL}${this.mixinViewModuleOptions.deleteIsBatch ? '' : '/' + id}`,
      //     this.mixinViewModuleOptions.deleteIsBatch ? {
      //       'data': id ? [id] : this.dataListSelections.map(item => item[this.mixinViewModuleOptions.deleteIsBatchKey])
      //     } : {}
      //   ).then(({ data: res }) => {
      //     if (res.code !== 0) {
      //       return this.$message.error(res.msg)
      //     }
      //     this.$message({
      //       message: this.$t('prompt.success'),
      //       type: 'success',
      //       duration: 500,
      //       onClose: () => {
      //         this.getDataList()
      //       }
      //     })
      //   }).catch(() => {})
      // }).catch(() => { })
    },
    // 导出
    exportHandle() {
      // var params = qs.stringify({
      //   'token': Cookies.get('token'),
      //   ...this.dataForm
      // })
      // window.location.href = `${window.SITE_CONFIG['apiURL']}${this.mixinViewModuleOptions.exportURL}?${params}`
    }
  }
}
</script>
